package com.managertrade.dao.mysql.repository;
import com.managertrade.dao.mysql.entity.DistributedLock;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.repository.query.Param;

public interface DistributedLockRepository extends JpaRepository<DistributedLock, String> {

    /**
     * 尝试获取锁（仅当锁不存在时插入，返回1表示成功）
     * MySQL：利用 INSERT IGNORE 防止重复主键异常
     */
    @Modifying
    @Transactional
    @Query(value = "INSERT IGNORE INTO distributed_lock(lock_name, locked_by) VALUES(:lockName, :lockedBy)", nativeQuery = true)
    int acquireLock(@Param("lockName") String lockName, @Param("lockedBy") String lockedBy);

    /**
     * 释放锁
     */
    @Modifying
    @Transactional
    @Query(value = "DELETE FROM distributed_lock WHERE lock_name = :lockName AND locked_by = :lockedBy", nativeQuery = true)
    int releaseLock(@Param("lockName") String lockName, @Param("lockedBy") String lockedBy);
}